package com.bl.andr.notificationlib;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Random;

/**
 * DESC: 通知管理类
 * TIME:2019-07-02
 */
public class NotifyManager {

    private Context context;
    private NotificationManager notificationManager;
    private Random random;

    public NotifyManager(@NonNull Context context) {
        this.context = context.getApplicationContext();
        init();
    }

    private void init() {
        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        random = new Random();
    }


///////////////////////////////////////////////////////////////////////////
// 渠道创建
///////////////////////////////////////////////////////////////////////////

    /**
     * 创建渠道
     *
     * @param channelEntity 渠道消息
     */
    public void createChannel(ChannelEntity channelEntity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createChannel(channelEntity, null);
        }
    }

    /**
     * 创建渠道组和一个渠道
     *
     * @param groupId   渠道组ID
     * @param groupName 渠道组名称
     * @param channel   渠道
     */
    public void createGroupWithChannel(@NonNull String groupId, @Nullable String groupName, @NonNull ChannelEntity channel) {
        ArrayList<ChannelEntity> channelList = new ArrayList<>();
        channelList.add(channel);
        createGroupWithChannel(groupId, groupName, channelList);
    }

    /**
     * 创建渠道组和一组渠道
     *
     * @param groupId     渠道组ID
     * @param groupName   渠道组名称
     * @param channelList 渠道s
     */
    public void createGroupWithChannel(@NonNull String groupId, @Nullable String groupName, @NonNull ArrayList<ChannelEntity> channelList) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            if (!TextUtils.isEmpty(groupId)) {
                createChannelGroup(groupId, groupName);
            }

            for (ChannelEntity channel : channelList) {
                createChannel(channel, groupId);
            }
        }
    }

    /**
     * 创建渠道，并创建组
     *
     * @param channelEntity 渠道配置信息
     * @param groupId       渠道组ID
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createChannel(@NonNull ChannelEntity channelEntity, @Nullable String groupId) {
        NotificationChannel channel = new NotificationChannel(
                channelEntity.getChannelId(), channelEntity.getChannelName(), channelEntity.getImportance()
        );

        channel.setShowBadge(channelEntity.isShowBadge());

        if (!TextUtils.isEmpty(channelEntity.getDescription()))
            channel.setDescription(channelEntity.getDescription());

        if (channelEntity.getSoundUri() != null) {
            channel.setSound(channelEntity.getSoundUri(), Notification.AUDIO_ATTRIBUTES_DEFAULT);
        }


        if (!TextUtils.isEmpty(groupId))
            channel.setGroup(groupId);

        notificationManager.createNotificationChannel(channel);
    }

    /**
     * 创建渠道组
     *
     * @param groupId   渠道组ID
     * @param groupName 渠道组名称
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createChannelGroup(@NonNull String groupId, @Nullable String groupName) {
        NotificationChannelGroup group = new NotificationChannelGroup(groupId, groupName);
        notificationManager.createNotificationChannelGroup(group);
    }


///////////////////////////////////////////////////////////////////////////
//  通知
///////////////////////////////////////////////////////////////////////////


    /**
     * 默认设置，调用方可以添加和修改
     *
     * @param channelId 渠道id
     */
    public NotificationCompat.Builder getDefaultBuilder(@NonNull String channelId) {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId);
        /*builder.setSmallIcon(R.drawable.push) // 必须要设置
                .setColor(Color.parseColor("#E92110"));*/
        return builder;
    }


    /**
     * 发送通知
     *
     * @param notification 通知具体内容
     * @return 通知Id
     */
    public int notifyNotify(@NonNull Notification notification) {
        int notifyId = getRandomId();
        return notifyNotify(notifyId, notification);
    }


    /**
     * 发送通知
     *
     * @param notifyId     通知Id
     * @param notification 通知具体内容
     * @return 通知Id
     */
    public int notifyNotify(int notifyId, @NonNull Notification notification) {
        notificationManager.notify(notifyId, notification);
        return notifyId;
    }

    /**
     * 关闭状态栏通知的显示
     *
     * @param notifyId 通知Id
     */
    public void cancelNotify(int notifyId) {
        notificationManager.cancel(notifyId);
    }


    /**
     * Generate a random integer
     *
     * @return int, [0, 50000)
     */
    private int getRandomId() {
        return random.nextInt(50000);
    }

///////////////////////////////////////////////////////////////////////////
// 渠道管理
///////////////////////////////////////////////////////////////////////////

    /**
     * 检查当前渠道的通知是否可用，Android O及以上版本调用
     * 注：areNotificationsEnabled()返回false时，即当前App通知被关时，此方法仍可能返回true，
     *
     * @param channelId 渠道Id
     * @return false：不可用
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public boolean areChannelsEnabled(@NonNull String channelId) {
        NotificationChannel notificationChannel = notificationManager.getNotificationChannel(channelId);
        return notificationChannel == null || notificationChannel.getImportance() != NotificationManager.IMPORTANCE_NONE;
    }

    /**
     * 检查通知是否可用
     *
     * @return false：不可用
     */
    public boolean areNotificationsEnabled() {
        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
        return notificationManagerCompat.areNotificationsEnabled();
    }


    /**
     * 手动打开应用通知
     *
     * @param channelId 渠道ID
     */
    public void jumpChannelSetting(@NonNull String channelId) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //适配 8.0及8.0以上(8.0需要先打开应用通知，再打开渠道通知)
            if (TextUtils.isEmpty(channelId)) {
                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
            } else {
                intent.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
                intent.putExtra(Settings.EXTRA_CHANNEL_ID, channelId);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//适配 5.0及5.0以上
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {// 适配 4.4及4.4以上
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else {
            intent.setAction(Settings.ACTION_SETTINGS);
        }
    }

///////////////////////////////////////////////////////////////////////////
// 渠道删除
///////////////////////////////////////////////////////////////////////////

    /**
     * 删除渠道
     *
     * @param channelId 渠道ID
     */
    public void deleteChannel(@NonNull String channelId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationManager.deleteNotificationChannel(channelId);
        }
    }

    /**
     * 删除组
     *
     * @param groupId 渠道组ID
     */
    public void deleteChannelGroup(@NonNull String groupId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationManager.deleteNotificationChannelGroup(groupId);
        }
    }
}
